﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Clock.Utils;

namespace Clock.ImageProcessing
{
    public class JBig2 : OsUtil
    {
        public static iTextSharp.text.Image ProcessImage(string imagePath)
        {
            Image img = Image.FromFile(imagePath);
            string newImage = imagePath;
            string symFilePath = newImage.Replace(Path.GetExtension(newImage), ".sym");
            string symIndexFilePath = newImage.Replace(Path.GetExtension(newImage), ".0000");

            CompressJBig2(newImage);

            iTextSharp.text.Image i = iTextSharp.text.ImgJBIG2.GetInstance(img.Width, img.Height, File.ReadAllBytes(symIndexFilePath), File.ReadAllBytes(symFilePath));
            TempData.Instance.Cleanup(symFilePath);
            TempData.Instance.Cleanup(symIndexFilePath);
            TempData.Instance.Cleanup(newImage);
     
            GC.Collect();

            return i;
        }

        public static iTextSharp.text.Image ProcessImage(Bitmap b)
        {

            var s = TempData.Instance.CreateTempFile(".jpg");
            b.Save(s, ImageFormat.Jpeg);

            return ProcessImage(s);
        }

        private static void CompressJBig2(string imagePath)
        {
            //-t .65
            string args = " -d -p -s -b " + '"' + imagePath.Replace(Path.GetExtension(imagePath), string.Empty) + '"' + " " + '"' + imagePath + '"';
           ProcessCommand(GetProgramPath("", "jbig2.exe"), args);
           

        }
    }
}
